package com.sondon.mayi.fragment;

import java.io.File;
import java.io.IOException;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sondon.mayi.activity.ChooseRegionActivity_;
import com.sondon.mayi.activity.LoginActivity_;
import com.sondon.mayi.activity.SetPasswdActivity_;
import com.sondon.mayi.activity.ShareActivity_;
import com.sondon.mayi.fruit.R;
import com.sondon.mayi.util.MyPrefs_;
import com.sondon.mayi.util.ToastUtils;

@EFragment(R.layout.config)
public class ConfigFragmentPage extends BaseFragment{
	@ViewById
	LinearLayout upgrade_msg_box;//升级会员
	@ViewById
	ImageView face;//头像I
	@ViewById
	TextView mobile;//手机号T
	@ViewById
	ImageView rank_pic;//等级头像I
	@ViewById
	TextView rank;//等级T
	@ViewById
	TextView upgrade;//等级升级T
	@ViewById
	TextView you_not_login;//没有登录T
	@ViewById
	LinearLayout version_box;//版本号L
	@ViewById
	TextView version_name;//版本T
//	@ViewById
//	ProgressBar waiting_verion;//版本进程P
	@ViewById
	LinearLayout upload_head_pic_box;//上传头像L
	@ViewById
	LinearLayout modify_region_box;//修改我的地区L
	@ViewById
	TextView region;//地区T
	@ViewById
	LinearLayout upload_contact_box;//上传更新通讯录L
	@ViewById
	LinearLayout addr_man;//收货地址管理
	@ViewById
	LinearLayout passwd_box;//密码设置
	@ViewById
	LinearLayout share;//分享
	@ViewById
	TextView kfphone;//客服电话
	@ViewById
	Button logout;//登出
	
	@Pref
	MyPrefs_ myprefs;
	
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	private static final int PICK_IMAGE_ACTIVITY_REQUEST_CODE = 200;
	
	
	@AfterViews
	public void initView(){
//		ToastUtils.show(getActivity(), R.string.processing);
		if(!myprefs.is_login().get()){
			upgrade_msg_box.setVisibility(View.GONE);
			you_not_login.setVisibility(View.VISIBLE);
		}else{
			
		}
	}
	
	@Click({R.id.logout,R.id.version_box,R.id.upload_head_pic_box
		,R.id.modify_region_box,R.id.upload_contact_box,
		R.id.addr_man,R.id.passwd_box,R.id.share,R.id.you_not_login})
	public void OnClick(View v){
		switch (v.getId()) {
		case R.id.logout:
			myprefs.is_login().remove();
			
			break;
		case R.id.you_not_login:
			break;
		case R.id.version_box:
			ToastUtils.show(getActivity(), "目前已经是最新版本");
			break;
		case R.id.upload_head_pic_box:
			if(!myprefs.is_login().get()){
				openActivity(LoginActivity_.class);
			}else{
				//选择图片来源：相册或者照相机
//				new Picture_PopupWindows(ConfigFragmentPage.this,face);
			}
			break;
		case R.id.modify_region_box:
			openActivity(ChooseRegionActivity_.class);
			break;
		case R.id.upload_contact_box:
			break;
		case R.id.addr_man:
			break;
		case R.id.passwd_box:
			openActivity(SetPasswdActivity_.class);
			break;
		case R.id.share:
			openActivity(ShareActivity_.class);
			break;
		
		default:
			break;
		}
	}
	
	
	
	
	
/*******************************************************拍照 相册*************************************************************/

	private static String picFileFullName;
	//拍照
    public void camera(){
    	String state = Environment.getExternalStorageState();  
        if (state.equals(Environment.MEDIA_MOUNTED)) {  
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
            File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);  
            if (!outDir.exists()) {  
            	outDir.mkdirs();  
            }  
            File outFile =  new File(outDir, System.currentTimeMillis() + ".jpg");  
            picFileFullName = outFile.getAbsolutePath();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));  
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);  
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);  
        } else{
        	Log.e(TAG, "请确认已经插入SD卡");
        }
    }
    
    //打开本地相册
    public void openAlbum(){
    	Intent intent = new Intent();
		intent.setAction(Intent.ACTION_PICK);

		intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, PICK_IMAGE_ACTIVITY_REQUEST_CODE);
    	
//    	Intent intent = new Intent();
//    	intent.setType("image/*");   
//        intent.setAction(Intent.ACTION_GET_CONTENT);   
//    	this.startActivityForResult(intent, PICK_IMAGE_ACTIVITY_REQUEST_CODE);
    }
    
 	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
 		super.onActivityResult(requestCode, resultCode, data);
 		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
 			if (resultCode ==getActivity().RESULT_OK) {
 				Log.e(TAG, "获取图片成功，path="+picFileFullName);
 				setImageView(picFileFullName);
 			} else if (resultCode ==getActivity().RESULT_CANCELED) {
 				// 用户取消了图像捕获
 			} else {
 				// 图像捕获失败，提示用户
 				Log.e(TAG, "拍照失败");
 			}
 		} else if (requestCode == PICK_IMAGE_ACTIVITY_REQUEST_CODE) {
 			if (resultCode == getActivity().RESULT_OK) {
 				Uri uri = data.getData();
 				if(uri != null){
 					String realPath = getRealPathFromURI(uri);
 					Log.e(TAG, "获取图片成功，path="+realPath);
 					setImageView(realPath);
 				}else{
 					Log.e(TAG, "从相册获取图片失败");
 				}
 			}
 		}
 	}
 	
 	private void setImageView(String realPath){
 		Bitmap bmp = BitmapFactory.decodeFile(realPath);
 		int degree = readPictureDegree(realPath);
 		if(degree <= 0){
 			face.setImageBitmap(bmp);
 		}else{
 			Log.e(TAG, "rotate:"+degree);
 			//创建操作图片是用的matrix对象
 	 		Matrix matrix=new Matrix();
 	 		//旋转图片动作
 	 		matrix.postRotate(degree);
 	 		//创建新图片
 	 		Bitmap resizedBitmap=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);
 	 		face.setImageBitmap(resizedBitmap);
 		}
 	}
 	

	public String getRealPathFromURI(Uri contentUri){
        try{
            String[] proj = {MediaStore.Images.Media.DATA};
            // Do not call Cursor.close() on a cursor obtained using this method, 
            // because the activity will do that for you at the appropriate time
            Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }catch (Exception e){
            return contentUri.getPath();
        }
	}
	
	/** 
     * 读取照片exif信息中的旋转角度<br/>
     * http://www.eoeandroid.com/thread-196978-1-1.html
     * 
     * @param path 照片路径 
     * @return角度 
     */  
    public static int readPictureDegree(String path) {  
            int degree  = 0;  
            try {  
                    ExifInterface exifInterface = new ExifInterface(path);  
                    int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);  
                    switch (orientation) {  
                    case ExifInterface.ORIENTATION_ROTATE_90:  
                            degree = 90;  
                            break;  
                    case ExifInterface.ORIENTATION_ROTATE_180:  
                            degree = 180;  
                            break;  
                    case ExifInterface.ORIENTATION_ROTATE_270:  
                            degree = 270;  
                            break;  
                    }  
            } catch (IOException e) {  
                    e.printStackTrace();  
            }  
            return degree;  
    }  
	
}	